<template>
    <div>
        <div class="e-form" v-if="dialogVisible === false">
            <div class="tabs" v-if="Object.keys(formData).length != 0">
                <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                    <!-- 基本信息 -->
                    <el-tab-pane
                        label="基本信息"
                        name="baseInfo"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="拟招标内容明细"
                        name="detail"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="招标清单"
                        name="tenderList"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="公文文件"
                        name="files"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="招标条款"
                        name="clause"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="附件信息"
                        name="attach"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="审核历史"
                        name="auditHistory"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="补遗记录"
                        name="recodes"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="关闭记录"
                        name="close"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane label="报名记录" name="reg" :disabled="clickTabFlag"></el-tab-pane>
                    <el-tab-pane
                        label="评标结果记录"
                        name="bidEvaluation"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="招标公示记录"
                        name="biddingPublicity"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <el-tab-pane
                        label="中标通知书记录"
                        name="bidWinningNotice"
                        :disabled="clickTabFlag"
                    ></el-tab-pane>
                    <div>
                        <div id="baseInfoCon" class="con">
                            <div class="tabs-title" id="baseInfo">基本信息</div>
                            <div style="width: 100%" class="form">
                                <el-form
                                    :model="formData"
                                    label-width="170px"
                                    :rules="rules"
                                    ref="ruleForm"
                                >
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="招标编号：" prop="billNo">
                                                <span>{{ formData.billNo }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="拟招标项目名称："
                                                prop="tenderName"
                                            >
                                                <span>{{ formData.tenderName }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <!-- kvId、name -->
                                            <el-form-item label="招标方式：" prop="tenderForm">
                                                <span>{{
                                                    formData.tenderForm | tenderForm(this)
                                                }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="招标类型：" prop="tenderType">
                                                <span>{{
                                                    formData.tenderType | tenderType(this)
                                                }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="项目名称：" prop="projectName">
                                                <div style="display: flex">
                                                    <span>{{ formData.projectName }}</span>
                                                    <!-- <el-button
                                                        style="margin-left: 10px"
                                                        class="btn-greenYellow"
                                                        size="mini"
                                                        @click="showBidding"
                                                        >查看</el-button
                                                    > -->
                                                </div>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="招标公告：" prop="tenderNotice">
                                                <el-button
                                                    style="width: 222px"
                                                    class="btn-greenYellow"
                                                    @click="handleNotice"
                                                    >招标公告
                                                </el-button>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="投标保证金（元）："
                                                prop="tenderBail"
                                            >
                                                <span>{{ formData.tenderBail }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <!-- id、name -->
                                            <el-form-item label="币种：" prop="currencyId">
                                                <span>{{ formData.currencyId | currencyId }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item
                                                label="拟招标金额（元）："
                                                prop="tenderAmount"
                                            >
                                                <span>{{
                                                    formData.tenderAmount === 0
                                                        ? '汇总计算包件的最高限价'
                                                        : formData.tenderAmount
                                                }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="税额：" prop="taxAmount">
                                                <span>{{
                                                    formData.taxAmount === 0
                                                        ? '汇总计算包件税额金额'
                                                        : formData.taxAmount
                                                }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="申请日期：" prop="applyTime">
                                                <span>{{ formData.applyTime }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="招标状态：" prop="tenderState">
                                                <span>{{
                                                    formData.tenderState | tenderState(this)
                                                }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="申请状态：" prop="state">
                                                <span>{{ formData.state | state(this) }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <!-- id、name -->
                                            <el-form-item label="申请单位：" prop="applyOrgName">
                                                <span>{{ formData.applyOrgName }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-form-item
                                            label="招标项目工程概况："
                                            prop="projectOverview"
                                        >
                                            <span>{{ formData.projectOverview }}</span>
                                        </el-form-item>
                                    </el-row>
                                    <el-row>
                                        <el-form-item label="备注：" prop="remarks">
                                            <span>{{ formData.remarks }}</span>
                                        </el-form-item>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="录入机构：" prop="orgName">
                                                <!-- 传id和名称 -->
                                                <span>{{ formData.orgName }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="招标单位：" prop="tenderUser">
                                                <span>{{ formData.tenderUser }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="本位币：" prop="baseCurName">
                                                <!-- 传id和名称 -->
                                                <span>{{ formData.baseCurName }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col
                                            :span="12"
                                            v-if="formData.baseCurName !== formData.currency"
                                        >
                                            <el-form-item label="人民币汇率：" prop="rmbRate">
                                                <span>{{ formData.rmbRate }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12" v-if="formData.tenderForm === '1'">
                                            <el-form-item label="发布时间：">
                                                <!-- 传id和名称 -->
                                                <span>{{ formData.relaseTime }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </div>
                        </div>

                        <div id="detailCon" class="con">
                            <div class="tabs-title" id="detail">拟招标内容明细</div>
                            <div>
                                <ComDetailsOfProposedIndex
                                    ref="ComDetailsOfProposedIndex"
                                    v-if="ifLoadComponent('detail') || detailsState"
                                    :tenderData="formData"
                                    :canEdit="false"
                                />
                                <div class="seize-a-seat" v-else>
                                    <i class="el-icon-loading"></i>
                                </div>
                            </div>
                        </div>

                        <div id="tenderListCon" class="con">
                            <div class="tabs-title" id="tenderList">招标清单</div>
                            <ComtenderListIndex
                                v-if="ifLoadComponent('tenderList')"
                                :tenderClass="formData.tenderClass"
                                :tenderListShow="tenderListShow"
                                :canEdit="false"
                            />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>

                        <div id="filesCon" class="con">
                            <div class="tabs-title" id="files">公文文件</div>
                            <div class="e-table">
                                <!-- 头部buttons -->
                                <div class="top" v-if="false">
                                    <div class="left">
                                        <div>
                                            <el-button size="small" @click="downFile"
                                                >下载</el-button
                                            >
                                            <el-button
                                                slot="reference"
                                                size="small"
                                                @click="deleteData('files')"
                                                >删除</el-button
                                            >
                                            <el-button
                                                size="small"
                                                style="padding: 10px 30px"
                                                class="btn-greenYellow"
                                                @click="clientSelect('docSelectData')"
                                                >选择公文</el-button
                                            >
                                        </div>
                                    </div>
                                </div>
                                <ComFilesIndex
                                    v-if="ifLoadComponent('files')"
                                    ref="ComFilesIndex"
                                    style="margin-top: -10px"
                                    :auditState="auditState"
                                />
                                <div class="seize-a-seat" v-else>
                                    <i class="el-icon-loading"></i>
                                </div>
                            </div>
                        </div>

                        <div id="clauseCon" class="con">
                            <div class="tabs-title" id="clause">通用合同条款</div>
                            <div class="e-table" style="min-height: auto">
                                <el-table
                                    :data="tableData"
                                    border
                                    style="width: 100%"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    :cell-class-name="cellClsNm"
                                >
                                    <el-table-column show-overflow-tooltip prop="a1" label="序号">
                                    </el-table-column>
                                    <el-table-column
                                        show-overflow-tooltip
                                        prop="a"
                                        label="所属单位"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        show-overflow-tooltip
                                        prop="b"
                                        label="通用合同条款编号"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        show-overflow-tooltip
                                        prop="c"
                                        label="合同条款名称"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        show-overflow-tooltip
                                        prop="d"
                                        label="条款明细查阅"
                                    >
                                    </el-table-column>
                                </el-table>
                                <ComPagination />
                            </div>

                            <div class="tabs-title" style="margin-top: 20px">项目专用合同条款</div>
                            <div class="e-table" style="min-height: auto; margin-bottom: 20px">
                                <div class="top">
                                    <div class="left">
                                        <div>
                                            <el-button size="small" class="btn-greenYellow"
                                                >新增</el-button
                                            >
                                            <el-button size="small" class="btn-greenYellow"
                                                >删除</el-button
                                            >
                                        </div>
                                    </div>
                                </div>
                                <el-table
                                    :data="tableData"
                                    border
                                    style="width: 100%"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    :cell-class-name="cellClsNm"
                                >
                                    <div class="top">
                                        <div class="left">
                                            <el-button size="mini">新增</el-button>
                                            <el-button size="mini">删除</el-button>
                                        </div>
                                    </div>
                                    <el-table-column show-overflow-tooltip prop="a1" label="序号">
                                    </el-table-column>
                                    <el-table-column show-overflow-tooltip prop="a" label="条目号">
                                    </el-table-column>
                                    <el-table-column
                                        show-overflow-tooltip
                                        prop="b"
                                        label="原条款内容"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        show-overflow-tooltip
                                        prop="c"
                                        label="专用合同条款内容"
                                    >
                                    </el-table-column>
                                </el-table>
                                <ComPagination />
                            </div>
                        </div>

                        <div id="attachCon" class="con">
                            <div class="tabs-title" id="attach">附件信息</div>
                            <ComAttachIndex v-if="ifLoadComponent('attach')" />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>

                        <!-- billType 工程施工招标6021 其他工程招标6022 物资供应招标6023 物资加工招标6024
                    周材租赁招标6025 服务采购招标6026 机材收入招标6027 设备采购招标6028
                    设备租赁招标6029 -->
                        <div id="auditHistoryCon" class="con">
                            <div class="tabs-title" id="auditHistory">审核历史</div>
                            <ComExaHistory
                                v-if="ifLoadComponent('auditHistory')"
                                billType="6021"
                                ref="ComExaHistory"
                            />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>

                        <div id="recodesCon" class="con">
                            <div class="tabs-title" id="recodes">补遗记录</div>
                            <ComTenderAddendumIndex v-if="ifLoadComponent('recodes')" />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>

                        <div id="closeCon" class="con">
                            <div class="tabs-title" id="close">关闭记录</div>
                            <ComBidClosingIndex v-if="ifLoadComponent('close')" />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>

                        <div id="regCon" class="con">
                            <div class="tabs-title" id="reg">报名记录</div>
                            <ComOpenBiddingRegIndex v-if="ifLoadComponent('reg')" />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>

                        <div id="bidEvaluationCon" class="con">
                            <div class="tabs-title" id="bidEvaluation">评标结果记录</div>
                            <ComBidEvaluationResultIndex v-if="ifLoadComponent('bidEvaluation')" />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>

                        <div id="biddingPublicityCon" class="con">
                            <div class="tabs-title" id="biddingPublicity">招标公示记录</div>
                            <ComBiddingResultIndex v-if="ifLoadComponent('biddingPublicity')" />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>

                        <div id="bidWinningNoticeCon">
                            <div class="tabs-title" id="bidWinningNotice">中标通知书记录</div>
                            <ComBidWinningNoticeIndex v-if="ifLoadComponent('bidWinningNotice')" />
                            <div class="seize-a-seat" v-else>
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>
                    </div>
                </el-tabs>
            </div>
            <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
            <!-- v-if="Object.keys(auditState).length !== 0" -->
            <div class="buttons">
                <ComBidButtons
                    :formData="formData"
                    @release="release"
                    ref="ComBidButtons"
                    releaseType="1"
                />
                <ComExaButtons
                    :auditState="auditState"
                    @exas="exas"
                    :founderId="formData.founderId"
                    :state="formData.state"
                    :isPrint="false"
                />
                <!-- <el-button type="primary" class="btn-blue" size="small">打印</el-button> -->
                <el-button @click="handleClose" size="small">取消</el-button>
            </div>
            <div class="buttons-seize-a-seat"></div>
        </div>
        <!-- dialog -->
        <ComNoticeDialog
            ref="ComNoticeDialog"
            :dialogVisible.sync="dialogVisible"
            :tenderClass="parseInt(formData.tenderClass)"
            :tenderForm="String(formData.tenderForm)"
            v-if="Object.keys(formData).length !== 0"
            :content="formData.tenderNotice"
            @save="noticeSave"
        />
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import applyRequest from '@/api/tender/apply.js'
import auditRequest from '@/api/tender/audit.js'
// import commonRequest from '@/api/tender/common.js'
// import ComTreeTable from '@/templates/table/treeTable.vue'
// import ComTreeFile from '@/templates/table/treeFile.vue'
import ComPagination from '@/components/pagination/pagination.vue'
import ComNoticeDialog from '@/components/common/noticeDialog.vue'
import ComExaHistory from '@/components/common/exaHistory.vue'
import ComTenderAddendumIndex from '@/pages/bidding/laborBidding/tenderAddendum/tenderAddendumIndex'
import ComBidClosingIndex from '@/pages/bidding/laborBidding/bidClosing/bidClosingIndex'
import ComBiddingResultIndex from '@/pages/bidding/laborBidding/biddingResult/biddingResultIndex'
import ComBidEvaluationResultIndex from '@/pages/bidding/laborBidding/bidEvaluationResult/bidEvaluationResultIndex'
import ComBidWinningNoticeIndex from '@/pages/bidding/laborBidding/bidWinningNotice/bidWinningNoticeIndex'
import ComOpenBiddingRegIndex from '@/pages/bidding/laborBidding/openBiddingReg/openBiddingRegIndex'
import ComDetailsOfProposedIndex from '@/pages/bidding/laborBidding/detailsOfProposed/detailsOfProposedIndex'
import ComAttachIndex from '@/components/common/attachIndex'
import ComFilesIndex from '@/pages/bidding/common/filesIndex'
import ComtenderListIndex from '@/pages/bidding/laborBidding/tenderList/tenderListIndex'
import ComExaButtons from '@/components/common/exaButtons'
import ComBidButtons from '@/components/bidding/bidButtons'
import authRequest from '@/api/identity/auth.js'
import tenderRequest from '@/api/tender/tender.js'
import { selectDataClient, openAppClient } from '@/utils/common'
import { mapState, mapMutations } from 'vuex'

export default {
    data () {
        const not0 = (rule, value, callback) => {
            if (typeof value === 'number' && value === 0) {
                return callback(new Error('数值不能为0'))
            } else {
                callback()
            }
        }
        const not0RmbRate = (rule, value, callback) => {
            if (typeof value === 'number' && value === 0) {
                return callback(new Error('请选择设置了人民币汇率的币种'))
            } else {
                callback()
            }
        }
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            formData: {},
            currentTabComponentName: '',
            selectData: [],
            orgSelectTableColumnAttr: [
                {
                    label: '机构Id',
                    prop: 'orgId'
                },
                {
                    label: '机构名称',
                    prop: 'orgName'
                }
            ],
            docSelectTableColumnAttr: [
                {
                    label: '序号'
                },
                {
                    label: '文件编号',
                    prop: 'docNum'
                },
                {
                    label: '公文文件名称',
                    prop: 'name'
                },
                {
                    label: '备案时间',
                    prop: 'oaCreateTime'
                },
                {
                    label: '备案人',
                    prop: 'userName'
                }
                // {
                //     label: '上传时间',
                //     prop: ''
                // }
            ],
            selectTableColumnWidth: {
                leftWidth: '150',
                rightWidth: '100'
            },
            selectDataPagination: {},
            loadComponent: new Set(),
            cloneFormDataStr: '',
            // 招标单据
            // 工程施工招标6021 其他工程招标6022 物资供应招标6023 物资加工招标6024 周材租赁招标6025 服务采购招标6026 机材收入招标6027 设备采购招标6028 设备租赁招标6029
            auditParams: {
                billId: this.$route.query.tenderId || this.$route.query.billid,
                billType: 6021,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            nullifyParams: {
                billId: this.$route.query.tenderId || this.$route.query.billid,
                billType: 6021,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            auditState: {},
            dialogVisible: false,
            tenderListShow: 0,
            rules: {
                billNo: { required: true, message: '请输入招标编号', trigger: 'blur' },
                tenderName: { required: true, message: '请输入拟招标项目名称', trigger: 'blur' },
                tenderForm: { required: true, message: '请选择招标方式', trigger: 'change' },
                tenderType: { required: true, message: '请选择招标类型', trigger: 'change' },
                projectName: { required: true, message: '请输入项目名称', trigger: 'blur' },
                tenderNotice: { required: true, message: '请输入公告', trigger: 'change' },
                tenderBail: [
                    { required: true, message: '请输入投标保证金（元）', trigger: 'blur' },
                    { type: 'number', message: '保证金必须为数字值' },
                    { validator: not0, trigger: 'blur' }
                ],
                currencyId: { required: true, message: '请选择币种', trigger: 'change' },
                tenderAmount: {
                    required: true,
                    message: '请输入拟招标金额（元）',
                    trigger: 'blur'
                },
                taxAmount: { required: true, message: '请输入税额', trigger: 'blur' },
                applyTime: { required: true, message: '请选择申请日期', trigger: 'change' },
                tenderState: { required: true, message: '请输入招标状态', trigger: 'blur' },
                state: { required: true, message: '请输入申请状态', trigger: 'blur' },
                applyOrgName: { required: true, message: '请选择申请单位', trigger: 'change' },
                projectOverview: [
                    {
                        required: true,
                        message: '请输入招标项目工程概况',
                        trigger: 'blur'
                    },
                    { max: 500, message: '最多允许输500个汉字', trigger: 'blur' }
                ],
                remarks: [
                    { required: true, message: '请输入备注', trigger: 'blur' },
                    { max: 500, message: '最多允许输500个汉字', trigger: 'blur' }
                ],
                orgName: { required: true, message: '请输入录入机构', trigger: 'blur' },
                tenderUser: { required: true, message: '请选择招标单位', trigger: 'change' },
                baseCurName: { required: true, message: '没有设置本位币，请联系集团信息化管理员设置！', trigger: 'blur' },
                rmbRate: [
                    { required: true, message: '请选择设置了人民币汇率的币种', trigger: 'change' },
                    { validator: not0RmbRate, trigger: 'change' }
                ]
            },
            tabsNameArr: [],
            detailsState: false
        }
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 40 - this.lastConHeight
        },
        ...mapState({
            options: state => state.biddingApplication.dictionaries,
            userInfo: state => state.userInfo
        }),
        tenderId () {
            return this.$route.query.tenderId || this.$route.query.billid
        }
    },
    watch: {
        // auditState: {
        //     handler (val) {
        //         if (val.canModify === false) {
        //             this.$router.push({
        //                 path: './biddingApplicationShow',
        //                 query: { tenderId: this.tenderId }
        //             })
        //         }
        //     },
        //     deep: true
        // }
    },
    components: {
        // ComTreeTable,
        // ComTreeFile,
        ComPagination,
        ComTenderAddendumIndex,
        ComBidClosingIndex,
        ComBiddingResultIndex,
        ComBidEvaluationResultIndex,
        ComBidWinningNoticeIndex,
        ComExaHistory,
        ComOpenBiddingRegIndex,
        ComDetailsOfProposedIndex,
        ComAttachIndex,
        ComFilesIndex,
        ComtenderListIndex,
        ComNoticeDialog,
        ComBidButtons,
        ComExaButtons
    },
    created () {
        ;(async () => {
            // 有依赖关系，先获取基础数据
            await this.getData()
            this.ifSeat()
        })()
        this.getCurrentUnitInfo()
    },
    mounted () {
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'detail',
            'tenderList',
            'files',
            'clause',
            'attach',
            'auditHistory',
            'recodes',
            'close',
            'reg',
            'bidEvaluation',
            'biddingPublicity',
            'bidWinningNotice'
        ]
        this.tabsNameArr = arr
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight(arr)
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item)?.offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
            // 加载组件时重新计算高度
            if (!this.ifLoadComponent(this.tabsName)) {
                this.diyWindowResize()
            }
            // 按需加载组件
            this.demandLoading({ name: this.tabsName })
            // this.loadComponent.add(this.tabsName)
            // 下滑过快可能导致计算高度不准确，下滑到最底部再重新计算
            if ($(document).scrollTop() + $(window).height() >= $(document).height() - 1) {
                setTimeout(() => {
                    this.diyWindowResize()
                }, 500)
            }
        })
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item)?.offsetTop
                return itemTop
            })
        })
    },
    beforeDestroy () {
        this.$notify.closeAll()
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setSelectedInfo']),
        release () {
            tenderRequest.tenderRelease(this.tenderId).then(() => {
                this.clientPop('suc', '发布成功')
            })
        },
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        detailRule () {
            // 拟招标内容明细验证
            const ruleMessageArr = []
            if (this.$refs?.ComDetailsOfProposedIndex) {
                const ComDetailsOfProposedIndex = this.$refs.ComDetailsOfProposedIndex
                if (ComDetailsOfProposedIndex.tableData.length === 0) {
                    ComDetailsOfProposedIndex.ruleMessage = '未添加包件'
                    this.onChangeTab({ name: 'detail' })
                    return
                }
                ComDetailsOfProposedIndex.tableData.forEach((item, index) => {
                    index += 1
                    if (item.itemNo === '') {
                        ruleMessageArr.push(`包件${index}包件编号不能为空`)
                    }
                    if (item.name == '') {
                        ruleMessageArr.push(`包件${index}包件名称不能为空`)
                    }
                    // 除了公开招标，其他招标方式分包商不能为空
                    if (this.formData.tenderForm !== '1' && item.subcontractor.length < 3) {
                        if (item.subcontractor.length === 0) {
                            ruleMessageArr.push(`包件${index}分包商不能为空`)
                        } else {
                            // 邀请招标、询价
                            if (
                                (this.formData.tenderForm === '0' ||
                                    this.formData.tenderForm === '2') &&
                                item.subcontractor.length < 3
                            ) {
                                ruleMessageArr.push(`包件${index}至少选择三家分包商`)
                                // 竞争性谈判
                            } else if (
                                this.formData.tenderForm === '3' &&
                                item.subcontractor.length < 2
                            ) {
                                ruleMessageArr.push(`包件${index}至少选择两家分包商`)
                            } else if (
                                this.tenderData.tenderForm === '4' &&
                                item.subcontractor.length < 1
                            ) {
                                ruleMessageArr.push(`包件${index}至少选择一家分包商`)
                            }
                        }
                    }
                    if (typeof item.taxRate !== 'number') {
                        ruleMessageArr.push(`包件${index}税率必须为数字`)
                    } else if (item.taxRate < 0 || item.taxRate > 100) {
                        ruleMessageArr.push(`包件${index}税率必须在0-100之间`)
                    }
                    if (typeof item.taxAmount !== 'number') {
                        ruleMessageArr.push(`包件${index}税额必须为数字`)
                    }
                    if (ruleMessageArr.length !== 0) {
                        ComDetailsOfProposedIndex.ruleMessage = ruleMessageArr.join('，')
                        this.onChangeTab({ name: 'detail' })
                    }
                })
            }
            if (ruleMessageArr.length === 0) {
                return true
            } else {
                return false
            }
        },
        // 保存
        saveAllData (notice = true) {
            return new Promise((resolve, reject) => {
                // 基础验证
                this.$refs.ruleForm.validate(async valid => {
                    if (valid) {
                        // 包件验证
                        if (this.detailRule()) {
                            // 清单验证暂未做
                            // 基础信息更新
                            const promise1 = applyRequest.tenderApplyUpdate(this.formData)
                            // 拟招标内容明细更新
                            const promise2 = (() => {
                                if (this.$refs?.ComDetailsOfProposedIndex) {
                                    return this.$refs.ComDetailsOfProposedIndex.save()
                                }
                            })()
                            Promise.all([promise1, promise2]).then(() => {
                                resolve()
                                if (!notice) return
                                this.clientPop('suc', '保存成功')
                            })
                            // 未通过包件验证
                        } else {
                            reject()
                        }
                        // 未通过基础验证
                    } else {
                        reject()
                        this.onChangeTab({ name: 'baseInfo' })
                        // this.clientPop('err', '有必填项未填写')
                        return false
                    }
                })
            })
        },
        noticeSave (content) {
            this.formData.tenderNotice = content
        },
        handleNotice () {
            this.dialogVisible = true
        },
        nullify () {},
        deleteData (type) {
            type
            const length = this.$refs.ComFilesIndex.selection.length
            this.clientPop(
                'info',
                `已选择【${length}】条数据，确定要删除吗？数据删除后不可恢复，请谨慎操作！`,
                this.delFiles
            )
        },
        downFile () {
            this.$refs.ComFilesIndex.downFile()
        },
        delFiles () {
            this.$refs.ComFilesIndex.delFiles()
        },
        diyWindowResize () {
            if (document.createEvent) {
                var event = document.createEvent('HTMLEvents')
                event.initEvent('resize', true, true)
                window.dispatchEvent(event)
            } else if (document.createEventObject) {
                window.fireEvent('onresize')
            }
        },
        ifLoadComponent (component) {
            if (component === undefined) return
            return this.loadComponent.has(component)
        },
        ifSeat () {
            if (this.$route.query.seat) {
                this.tabsName = this.$route.query.seat
                this.onChangeTab(this.$route.query.seat)
            }
        },
        showBidding () {
            // 客户端弹窗弹出本地页面
            openAppClient(`/biddingApplicationShow?see=true&tenderId=${this.tenderId}`, '查看招标')
        },
        handleClose () {
            this.$router.push('biddingApplication')
        },
        // 获取最后一个内容区域的高度  ，计算底部空白
        getLastConHeight (arr) {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById(arr[length - 1] + 'Con')) {
                    const lastConHeight = document.getElementById(
                        arr[length - 1] + 'Con'
                    )?.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        async demandLoading (e) {
            this.loadComponent.add(e.name)
            if (e.name === 'tenderList') {
                this.tenderListShow += 1
            }
            const nextComponent = this.tabsNameArr.find(
                (value, index) =>
                    index === this.tabsNameArr.findIndex(value => value === e.name) + 1
            )
            const nextComponent2 = this.tabsNameArr.find(
                (value, index) =>
                    index === this.tabsNameArr.findIndex(value => value === e.name) + 2
            )
            this.loadComponent.add(nextComponent)
            this.loadComponent.add(nextComponent2)
        },
        onChangeTab (e) {
            if (!e.name) {
                let temp = e
                e = {}
                e.name = temp
            }
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
            // 加载组件时重新计算高度
            if (!this.ifLoadComponent(this.tabsName)) {
                this.diyWindowResize()
            }
            // 按需加载组件
            this.demandLoading(e)
        },
        clientSelect (name, company) {
            if (name === 'orgSelectData') {
                selectDataClient({
                    SelectServiceToken: '/hr/org/getChildrenOrg', // 客户端对应方法名
                    IsSingleMode: true, // 是否单选 true 单选 false 多选
                    SelectedIDs: [], // 已选中id
                    Title: '选择申请单位' // 标题
                }).then(val => {
                    if (company === 'applyOrgName') {
                        this.formData.applyOrgId = val[0].applyOrgId
                        this.formData.applyOrgName = val[0].orgName
                    } else {
                        this.formData.tenderUserId = val[0].applyOrgId
                        this.formData.tenderUser = val[0].orgName
                    }
                    // // 保存用户选择返回数据到store
                    // this.setSelectedInfo(val)
                    // // 客户端弹窗预览结果
                    // // 参数依次为: 打开页面地址、标题、回调函数
                    // openAppClient('/showSelectedData', '选择结果', function () {})
                })
            } else if (name === 'docSelectData') {
                selectDataClient({
                    SelectServiceToken: '/tender/document/listByEntity', // 客户端对应方法名
                    IsSingleMode: true, // 是否单选 true 单选 false 多选
                    SelectedIDs: [], // 已选中id
                    Title: '选择公文', // 标题
                    OrgId: this.userInfo.orgInfo.orgId
                }).then(val => {
                    this.$refs.ComFilesIndex.tableData = val.list
                    // // 保存用户选择返回数据到store
                    // this.setSelectedInfo(val)
                    // // 客户端弹窗预览结果
                    // // 参数依次为: 打开页面地址、标题、回调函数
                    // openAppClient('/showSelectedData', '选择结果', function () {})
                })
            }
        },
        currentTabComponent (name) {
            return this.currentTabComponentName === name
        },
        selectChange (kvId, label) {
            if (label === '招标方式') {
                this.options.tenderForm.forEach(item => {
                    if (kvId === item.value) {
                        this.formData.tenderFormName = item.label
                    }
                })
            } else if (label === '币种') {
                let index
                this.options.currency.forEach((item, key) => {
                    if (item.kvValue === kvId) {
                        index = key
                        this.formData.currency = item.kvKey
                    }
                })
                authRequest
                    .getRmbRate({
                        currency: index,
                        orgId: this.userInfo.orgInfo.orgId
                    })
                    .then(res => {
                        this.formData.rmbRate = res.rate
                    })
                    .catch(() => {
                        this.formData.rmbRate = 0
                    })
            } else if (label === '招标类型') {
                this.options.tenderType.forEach((value, key) => {
                    if (kvId === key) {
                        this.formData.tenderTypeName = value
                    }
                })
            } else if (label === '项目名称') {
                ;('等待接口')
            }
        },
        noFocus () {
            this.$refs.noFocus1?.blur()
            this.$refs.noFocus2?.blur()
        },
        async getData () {
            await applyRequest.tenderApplyFindById(this.tenderId).then(res => {
                this.formData = res
                this.cloneFormDataStr = JSON.stringify(res)
                // res
                // this.formData.tenderState = 0 //假数据
            })
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        }
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}
</style>
